package com.hsl.housaileibot001.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 性能指标收集器
 * 用于实时监控 AI 接口的性能
 */
@Component
public class PerformanceMetrics {
    private static final Logger logger = LoggerFactory.getLogger(PerformanceMetrics.class);

    // 请求统计
    private final ConcurrentHashMap<String, RequestStats> statsMap = new ConcurrentHashMap<>();

    /**
     * 记录请求
     */
    public void recordRequest(String endpoint, long durationMs, boolean success) {
        statsMap.computeIfAbsent(endpoint, k -> new RequestStats())
                .record(durationMs, success);
    }

    /**
     * 获取统计信息
     */
    public void printStats() {
        logger.info("========== AI 接口性能统计 ==========");
        statsMap.forEach((endpoint, stats) -> {
            logger.info("端点: {}", endpoint);
            logger.info("  总请求数: {}", stats.totalRequests.get());
            logger.info("  成功请求: {}", stats.successRequests.get());
            logger.info("  失败请求: {}", stats.failedRequests.get());
            logger.info("  平均响应时间: {}ms", stats.getAverageTime());
            logger.info("  最小响应时间: {}ms", stats.minTime.get());
            logger.info("  最大响应时间: {}ms", stats.maxTime.get());
            logger.info("  成功率: {:.2f}%", stats.getSuccessRate());
        });
        logger.info("=====================================");
    }

    /**
     * 清空统计
     */
    public void reset() {
        statsMap.clear();
    }

    /**
     * 请求统计类
     */
    public static class RequestStats {
        private final AtomicLong totalRequests = new AtomicLong(0);
        private final AtomicLong successRequests = new AtomicLong(0);
        private final AtomicLong failedRequests = new AtomicLong(0);
        private final AtomicLong totalTime = new AtomicLong(0);
        private final AtomicLong minTime = new AtomicLong(Long.MAX_VALUE);
        private final AtomicLong maxTime = new AtomicLong(0);

        public void record(long durationMs, boolean success) {
            totalRequests.incrementAndGet();
            totalTime.addAndGet(durationMs);

            if (success) {
                successRequests.incrementAndGet();
            } else {
                failedRequests.incrementAndGet();
            }

            // 更新最小值
            minTime.getAndUpdate(current -> Math.min(current, durationMs));

            // 更新最大值
            maxTime.getAndUpdate(current -> Math.max(current, durationMs));
        }

        public long getAverageTime() {
            long total = totalRequests.get();
            return total == 0 ? 0 : totalTime.get() / total;
        }

        public double getSuccessRate() {
            long total = totalRequests.get();
            return total == 0 ? 0 : (successRequests.get() * 100.0) / total;
        }
    }
}
